<template>
  <div>
    <PageTemplate>
      <div slot="content">
        <PageEditCollapse :is-search="false" :default-collapse="true">
          <div slot="title" class="page-edit-colllapse-title">
            <div style="width: 200px;">{{$t('cm.baseinfo')}}</div>
          </div>
          <div>
            <!-- 表单 -->
            <el-form
              :model="Knowledge"
              label-position="right"
              label-width="150px"
              class="page-edit-colllapse-form"
              :rules="rules"
              ref="Knowledge"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.knowledge_code')" prop="knowledgeCode">
                    <el-input v-model="Knowledge.knowledgeCode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.knowledge_type')" prop="knowledgeType">
                    <!--<el-input v-model="Knowledge.knowledgeType"></el-input>-->
                    <el-select v-model="Knowledge.knowledgeType" filterable placeholder="请选择">
                      <el-option
                        v-for="(item, index) in knowledgeTypes"
                        :key="index"
                        :label="item.dictText"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.knowledge_year')" prop="year">
                    <el-input v-model="Knowledge.year"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.award_principal_user')" prop="principalUser">
                    <!--<el-input v-model="Knowledge.principalUser"></el-input>-->
                    <PersonSelect id="principalUser" :value="Knowledge.principalUser" v-bind:multiple="false"  ></PersonSelect>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.knowledge_invent_user')" prop="inventUser">
                    <!--<el-input v-model="Knowledge.inventUser"></el-input>-->
                    <PersonSelect id="inventUser" :value="Knowledge.inventUser" v-bind:multiple="true"  ></PersonSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.knowledge_authorization')" prop="authorization">
                    <el-radio v-model="Knowledge.authorization" label="Y">授权</el-radio>
                    <el-radio v-model="Knowledge.authorization" label="N">受理</el-radio>
                    <el-radio v-model="Knowledge.authorization" label="P">PCT申请</el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_deptName')" prop="deptName">
                    <el-select v-model="Knowledge.deptName" filterable placeholder="请选择">
                      <el-option
                        v-for="(item, index) in subjectDepts"
                        :key="index"
                        :label="item.dictText"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item :label="$t('sri.allowDownloadPerson')">
                    <PersonSelect id="participant" :value="participant" @input="(v) => {participant = v}" v-bind:multiple="true"  ></PersonSelect>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item :label="$t('sri.knowledge_certificate')">
                    <el-input v-model="Knowledge.fileName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </PageEditCollapse>
        <PageEditCollapse :is-search="false" :default-collapse="true"  v-if="this.isExistNameNumber>-1">
          <div slot="title" class="page-edit-colllapse-title">
            <div style="width: 200px;">成果文件</div>
          </div>
          <div>
            <FileUploadCommon
              @uploadSuccess="uploadSuccess"
              @uploadRemove="uploadRemove"
              :fileList="fileList"
              >
              </FileUploadCommon>
          </div>
        </PageEditCollapse>
        <el-row class="row-empty-10"></el-row>
        <el-row>
          <el-button type="primary" @click="submitForm('Knowledge')">{{$t('cm.commit')}}</el-button>
          <el-button type="primary" @click="toList">{{$t('cm.return')}}</el-button>
        </el-row>
      </div>
    </PageTemplate>
  </div>
</template>

<script>
import { ALERT } from '@/utils/responseHandle'
import * as Constant from '@/utils/constant'
import PageTemplate from '@/components/common/PageTemplate'
import PageEditCollapse from '@/components/common/PageEditCollapse'
import FileUploadCommon from '@/components/common/FileUploadCommon'
import HasBtn from '@/mixins/HasBtn'
import { mapState } from 'vuex'
import { COMMON } from '@/utils/commonUtil'
import api_sri from '@/api/api_sri'
import sys_manage from '@/api/sys_manage'
import PersonSelect from '@/components/asc/PersonSelect'
import {getCurrentUserDetail} from '@/api/api.js'
const vailPrincipalUserName=(rule,value,callback)=>{
  if(document.getElementById("principalUser").value) {
    callback();
  }else{
    callback(new Error("必填项"));
  }
};

const vailInventUserName=(rule,value,callback)=>{
  if(document.getElementById("inventUser").value) {
    callback();
  }else{
    callback(new Error("必填项"));
  }
};

export default {
  components: {
    PageTemplate, PageEditCollapse, PersonSelect, FileUploadCommon
  },
  data () {
    return {
      Knowledge: {
        id: null,
        knowledgeCode: null,
        knowledgeType: null,
        year: null,
        principalUser: null,
        inventUser: null,
        authorization: null,
        deptId: 11,
        deptName: null,
        fileId: 1,
        fileName: null,
        createUserName:null
      },
      KnowledgeUsers:[],
      participant: null,
      knowledgeFiles: [],
      isExistName:null,
      isExistNameList:[],
      isExistNameNumber:-1,
      subjectDepts: [],
      knowledgeTypes: [],
      rules: {
        knowledgeCode: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        knowledgeType: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        year: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        principalUser: [
          { required: true, validator: vailPrincipalUserName, trigger: 'blur' }
        ],
        inventUser: [
          { required: true, validator: vailInventUserName, trigger: 'blur' }
        ],
        authorization: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      fileList: []
    }
  },
  created () {
    this.sysDictLoadByPaging();
    if (this.$router.history.current.params.id !== Constant.NEW_PARAMS) {
      this.sriGainIprGet(this.$router.history.current.params.id)
      this.getNowUser()
    }
  },
  methods: {
    getNowUser () {
                let _this = this;
                getCurrentUserDetail({}).then((result) => {
                  if (result.status == "200" && result.data.code == "0") {
                    this.isExistName =this.participant+","+this.Knowledge.createUserName+","+this.Knowledge.principalUser
                    var temp = this.isExistName.split(",");
                      for (var i=0; i<temp.length; i++) {
                        this.isExistNameList.push(temp[i])
                      }

                      this.isExistNameNumber=this.isExistNameList.indexOf(result.data.data.userName)
                     //console.log("srigaintopic-username",this.isExistNameList);
                      //console.log("srigaintopic-username",this.isExistNameList.indexOf("[P206192]叶亮"));
                  } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                  }
                }).catch((err) => {
                  _this.$alert(err,_this.$t('cm.tips'));
                });
             },
    sriGainIprGet (id) {
      api_sri.sriGainIprGet({ id }, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.Knowledge = result.data.knowledge;
          this.KnowledgeUsers = result.data.knowledgeUsers;
          if (this.KnowledgeUsers.length > 0) {
            var temps = [];
            for (var i=0; i<this.KnowledgeUsers.length; i++) {
              var temp = "[" + this.KnowledgeUsers[i].participantId + "]" + this.KnowledgeUsers[i].participantName;
              temps.push(temp);
            }
            this.participant = temps.join(",");
          }
          this.fileList = result.data.knowledgeFiles.map(item => {
            return {
              name: item.fileName,
              url: item.filePath,
              fileId: item.fileId
            }
          })
        } else {
          // _this.$t('cm.tips')
          ALERT.error(result.msg)
        }
      })
    },
    sysDictLoadByPaging () {
      sys_manage.sysDictLoadByPaging({dictGroupKey: 'achievement_profession_dept'}, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.subjectDepts = result.data
        } else {
          ALERT.error(result.msg)
        }
      })
      sys_manage.sysDictLoadByPaging({dictGroupKey: 'intellectual_property_type'}, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.knowledgeTypes = result.data
        } else {
          ALERT.error(result.msg)
        }
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.Knowledge.principalUser = document.getElementById("principalUser").value;
          this.Knowledge.inventUser = document.getElementById("inventUser").value;
          if (this.participant != null) {
            var temp = this.participant.split(",");
            for (var i=0; i<temp.length; i++) {
              var endIndx = temp[i].indexOf("]");
              var id = temp[i].substring(1,endIndx);
              var name = temp[i].substring(endIndx+1);
              var curUsers = {"participantId":id, "participantName":name};
              this.KnowledgeUsers.push(curUsers);
            }
          }
          let d = {
            knowledge: this.Knowledge,
            knowledgeUsers: this.KnowledgeUsers
          }
          let knowledgeFiles = this.fileList.map(item => {
            return {
              knowledgeId: this.Knowledge.id,
              fileId: item.fileId,
              fileName: item.name,
              filePath: item.url
            }
          })
          d.knowledgeFiles = knowledgeFiles
          api_sri.sriGainIprSave(d, result => {
            if (result.code === Constant.RT_SUCCESS) {
              ALERT.success(result.msg)
              this.toList()
            } else {
              // _this.$t('cm.tips')
              ALERT.error(result.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    toList () {
      COMMON.routerTo(Constant.ROUTE_SRI_GAIN_IPR.index, this.$router)
    },
    selectAllowDownloadPerson() {},
    uploadSuccess (res, fileKey) {
      if (res.data && res.data[0]) {
        let file = {name: res.data[0].fileName, url: res.data[0].url, fileId: res.data[0].fileId}
        this.fileList.push(file)
      }
    },
    uploadRemove (fileList, fileKey) {
      let resList = fileList.map(item => {
        return {
          name: item.name,
          url: item.url,
          fileId: item.fileId
        }
      })
      this.fileList = resList
    }
  },
  mounted () {
  },
  computed: {
  }
}
</script>

<style lang="scss">
</style>
